import threading
import time
import thread

class mul_exe(threading.Thread):

	def __init__(self,rank=None):
		threading.Thread.__init__(self)
		self.task_count = len(mul_exe.taskletQueue)
		if rank == None:
			rank = self.task_count +1
		
		
		self.this_rank = rank
		mul_exe.channel.append(self.this_rank)


	def __call__(self,call_func):
		return self.mul_run(call_func)
		
		
	def mul_run(self,call_func):
		def _deco(*argc,**kargs):
			mul_exe.argc[self.this_rank] = argc
			mul_exe.kargs[self.this_rank] = kargs
			mul_exe.taskletQueue[self.this_rank] = call_func
			if (self.isAlive()):
				print "now func run"
				return self.join(4)
			return self.start()
		return _deco


	def run(self):
		if mul_exe.taskletQueue.has_key(self.this_rank):
			return mul_exe.taskletQueue[self.this_rank] (* mul_exe.argc[self.this_rank],** mul_exe.kargs[self.this_rank])
		else:
			raise NameError()

	@staticmethod
	def Mul_run(call):
		def _deco(*argc,**kargs):
			return thread.start_new_thread(call,tuple(argc),(kargs))

		return _deco

	# @staticmethod
	# def isStop():
	# 	if len(mul_exe.channel) == 0:
	# 		return True
	# 	else :
	# 		return False



mul_exe.taskletQueue = {}
mul_exe.channel = [0]
mul_exe.argc = {}
mul_exe.kargs = {}


@mul_exe.Mul_run
def test(count,channel):
	name = count
	while count>0:
		print "thread : %d"% name ,count 
		count -= 1
		time.sleep(count/2)
	channel.append(name)


if __name__ == "__main__":
	t = test(6,mul_exe.channel)
	t2 =test(4,mul_exe.channel)

	while 1:
		while (len(mul_exe.channel) != 0):
			print mul_exe.channel.pop()
		pass

		
